package com.cmccgz.udacs_landlord_webapp.main.user.login;

import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cmccgz.baselibrary.base.BaseActivity;
import com.cmccgz.baselibrary.base.BaseFragment;
import com.cmccgz.baselibrary.utils.StringUtils;
import com.cmccgz.udacs_landlord_webapp.R;
import com.cmccgz.udacs_landlord_webapp.base.AppConfig;
import com.cmccgz.udacs_landlord_webapp.bean.LoginInfo;
import com.cmccgz.udacs_landlord_webapp.bean.UserInfo;
import com.cmccgz.udacs_landlord_webapp.interfaces.OnGetSmsKeyListenter;
import com.cmccgz.udacs_landlord_webapp.main.host.CHostActivity;
import com.cmccgz.udacs_landlord_webapp.main.host.HostActivity;
import com.cmccgz.udacs_landlord_webapp.main.user.userinfo.UserInfoContract;
import com.cmccgz.udacs_landlord_webapp.main.user.userinfo.UserInfoPresenter;
import com.cmccgz.udacs_landlord_webapp.observers.SmsObserver;
import com.cmccgz.udacs_landlord_webapp.utils.ViewHelper;


/**
 * @author: INX
 * 登陆fragment
 */

public class LoginFragment extends BaseFragment implements LoginContract.LoginView, View.OnClickListener ,UserInfoContract.UserInfoView, OnGetSmsKeyListenter {

    private LoginContract.LoginPresenter loginPresenter;
    private UserInfoContract.UserInfoPresenter userInfoPresenter;
    private EditText et_un;
    private EditText et_pwd;
    private Button btn_login;
    private ViewHelper mViewHelper;
    private TextView tv_forget_pwd;
    private boolean isTest=false,isRecever;//是否测试，是否反转角色类型
    private TextView tv_sms_type;
    private TextView tv_pwd_type;
    private RelativeLayout rl_login_pwd;
    private RelativeLayout rl_login_sms;
    private TextView tv_getCode;
    private SmsObserver smsObserver;
    private boolean isRegisterSMSObserver;
    private View v_line_left;
    private View v_line_right;
    private EditText et_un_sms;
    private EditText et_sms_key;
    private Button btn_login_sms;

    public LoginFragment() {
    }

    public static LoginFragment newInstance() {
        return new LoginFragment();
    }

    @Override
    protected int setLayoutId() {
        return R.layout.fragment_login;
    }

    @Override
    protected void initView() {
        loginPresenter=new LoginPresenter(this);
        userInfoPresenter=new UserInfoPresenter(this);
        et_un = ((EditText) findViewById(R.id.et_un));
        et_pwd = ((EditText) findViewById(R.id.et_pwd));
        btn_login = ((Button) findViewById(R.id.btn_login));
        tv_forget_pwd = ((TextView) findViewById(R.id.tv_forget_pwd));
        tv_pwd_type = ((TextView) findViewById(R.id.tv_pwd_type));
        tv_sms_type = ((TextView) findViewById(R.id.tv_sms_type));
        rl_login_pwd = ((RelativeLayout) findViewById(R.id.rl_login_pwd));
        rl_login_sms = ((RelativeLayout) findViewById(R.id.rl_login_sms));
        tv_getCode = ((TextView) findViewById(R.id.tv_getCode));
        v_line_left = findViewById(R.id.v_line_left);
        v_line_right = findViewById(R.id.v_line_right);
        et_un_sms = ((EditText) findViewById(R.id.et_un_sms));
        et_sms_key = ((EditText) findViewById(R.id.et_sms_key));
        btn_login_sms = ((Button) findViewById(R.id.btn_login_sms));
        tv_getCode.setOnClickListener(this);
        btn_login_sms.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        tv_forget_pwd.setOnClickListener(this);
        tv_pwd_type.setOnClickListener(this);
        tv_sms_type.setOnClickListener(this);
        mViewHelper = ViewHelper.instance(this);
        if (mViewHelper!=null) {
            mViewHelper.setTitle(R.string.title_login);
            mViewHelper.setAllVisable(false);
        }
        if (isTest) {
            btn_login.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    isRecever=true;
                    showConfirmDialog("提示", "当前是长按切换反转角色类型！", "确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (alertDialog!=null) {
                                alertDialog.dismiss();
                            }
                            showLoadingDialog(getString(R.string.loading_login));
                            loginPresenter.doLogin(et_un.getText().toString(),et_pwd.getText().toString(),LoginPresenter.TYPE_PWD);
                        }
                    }, "取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            if (alertDialog!=null) {
                                alertDialog.dismiss();
                            }
                        }
                    });
                    return false;
                }
            });
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        loginPresenter.start();
    }

    /**
     * 登陆请求成功
     * @param loginInfo
     */
    @Override
    public void loginSuccess(LoginInfo loginInfo) {
        //长按则转换角色类型
        if (isTest&&isRecever) {
            String user_type = loginInfo.getUser_type();
            loginInfo.setUser_type(getString(R.string.type_custemer).equals(user_type)?
                    getString(R.string.type_landlord):
                    getString(R.string.type_custemer));
        }
        AppConfig.setMobile(mContext,loginInfo.getMobile());
        AppConfig.setToken(mContext,loginInfo.getToken());
        AppConfig.setUserType(mContext,loginInfo.getUser_type());
        AppConfig.setUserType(mContext,loginInfo.getUser_type());
//        JPushInterface.setAlias(mContext, 0, loginInfo.getMobile());
        //角色为租客的时候需要二次请求获取用户信息
        if (getString(R.string.type_custemer).equals(loginInfo.getUser_type())) {
           userInfoPresenter.getUserInfo();
        }else{
            dismissLoadingDialog();
            showToast(R.string.tips_login_success);
            startActivity(new Intent(mContext, HostActivity.class));
            ((BaseActivity) mContext).finish(false);
        }

        AppConfig.seAccendant(mContext,"0".equals(loginInfo.getAccendant()));
    }

    /**
     * 登陆请求失败
     * @param msg
     */
    @Override
    public void loginError(String msg) {
        dismissLoadingDialog();
        showToast(msg);
    }

    @Override
    public void showUserHead(String url) {
        if (!TextUtils.isEmpty(url)){

        }
    }

    /**
     * 等待验证码
     * @param second
     */
    @Override
    public void waitCode(int second) {
        tv_getCode.setEnabled(false);
        tv_getCode.setText(second+"秒");
        if (second==0) {
            resetCode();
        }
    }

    /**
     * 获取验证码失败
     * @param msg
     */
    @Override
    public void getCodeError(String msg) {
        resetCode();
        showToast(msg);
    }

    /**
     * 获取验证码成功
     */
    @Override
    public void getCodeSuccess() {

    }

    /**
     * 充值验证码状态
     */
    @Override
    public void resetCode() {
        tv_getCode.setEnabled(true);
        tv_getCode.setText(R.string.get_code);
    }
    @Override
    public boolean isActive() {
        return isAdded();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                isRecever=false;
                showLoadingDialog(getString(R.string.loading_login));
                loginPresenter.doLogin(et_un.getText().toString(), et_pwd.getText().toString(),LoginPresenter.TYPE_PWD);
                break;
            case R.id.tv_forget_pwd:
                ((LoginActivity) mContext).forgetPwd(et_un.getText().toString());
                break;
            case R.id.tv_pwd_type:
                tv_pwd_type.setEnabled(false);
                tv_sms_type.setEnabled(true);
                v_line_left.setEnabled(false);
                v_line_right.setEnabled(true);
                rl_login_pwd.setVisibility(View.VISIBLE);
                rl_login_sms.setVisibility(View.GONE);
                if (!StringUtils.isEmpty(et_un_sms.getText().toString())) {
                    et_un.setText(et_un_sms.getText());
                }
                break;
            case R.id.tv_sms_type:
                tv_pwd_type.setEnabled(true);
                tv_sms_type.setEnabled(false);
                v_line_left.setEnabled(true);
                v_line_right.setEnabled(false);
                rl_login_pwd.setVisibility(View.GONE);
                rl_login_sms.setVisibility(View.VISIBLE);
                if (!isRegisterSMSObserver) {
                    isRegisterSMSObserver = true;
                    smsObserver = new SmsObserver(new Handler(),mContext,this);
                    mContext.getContentResolver().registerContentObserver(Uri.parse("content://sms/"), true, smsObserver);
                }
                if (!StringUtils.isEmpty(et_un.getText().toString())) {
                    et_un_sms.setText(et_un.getText());
                }
                break;
            case R.id.tv_getCode:
                loginPresenter.getCode(et_un_sms.getText().toString(),handler);
                break;
            case R.id.btn_login_sms:
                isRecever=false;
                showLoadingDialog(getString(R.string.loading_login));
                loginPresenter.doLogin(et_un_sms.getText().toString(), et_sms_key.getText().toString(),LoginPresenter.TYPE_SMS);
                break;
            default:
                break;
        }
    }

    @Override
    public void getUserInfoCache(UserInfo userInfo) {

    }

    /**
     * 获取用户信息成功（当type==0的时候，租客）
     * @param userInfo
     */
    @Override
    public void getUserInfoSuccess(UserInfo userInfo) {
        dismissLoadingDialog();
        showToast(R.string.tips_login_success);
        Intent intent = new Intent(mContext, CHostActivity.class);
        intent.putExtra(CHostActivity.KEY_USERINFO,userInfo);
        startActivity(intent);
        ((BaseActivity) mContext).finish(false);
    }

    /**
     * 获取用户信息失败
     * @param msg
     */
    @Override
    public void getUserInfoFail(String msg) {
        AppConfig.setMobile(mContext,"");
        showToast(msg);
    }

    public void stopObserver() {
        isRegisterSMSObserver=false;
        if (smsObserver!=null) {
            mContext.getContentResolver().unregisterContentObserver(smsObserver);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopObserver();
    }

    @Override
    public void onPause() {
        super.onPause();
        stopObserver();
    }
    @Override
    public void onDestroy() {
        if (loginPresenter!=null) {
            loginPresenter.onDestroy();
        }
        super.onDestroy();
    }

    @Override
    public void onChange(String smsKey) {
        if (StringUtils.isEmpty(smsKey)) return;
        et_sms_key.setText(smsKey);
        btn_login_sms.performClick();
    }


}
